﻿using AsscerMVCN2512.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;

namespace AsscerMVCN2512.Controllers
{
    public class AreaTypeController : Controller
    {
        private readonly AssetDBEntities1 db = new AssetDBEntities1();

        // 区域类别管理主页面
        public ActionResult Index()
        {
            return View();
        }

        // 获取区域类别列表
        [HttpPost]
        public ActionResult GetAreaTypeList(int page = 1, int limit = 10, string AreaTypeName = "")
        {
            try
            {
                var query = db.AreaTypeInfo.AsQueryable();

                // 查询条件
                if (!string.IsNullOrEmpty(AreaTypeName))
                {
                    query = query.Where(a => a.AreaTypeName.Contains(AreaTypeName));
                }

                var total = query.Count();
                var data = query.OrderBy(a => a.AreaTypeID)
                              .Skip((page - 1) * limit)
                              .Take(limit)
                              .Select(a => new
                              {
                                  a.AreaTypeID,
                                  a.AreaTypeName,
                                  a.AreaTypeMark
                              })
                              .ToList();

                return Json(new { code = 0, msg = "成功", count = total, data = data });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "获取数据失败：" + ex.Message });
            }
        }

        // 添加区域类别
        [HttpPost]
        public ActionResult AddAreaType(AreaTypeInfo areaType)
        {
            try
            {
                // 验证区域类别名称是否已存在
                var existingAreaType = db.AreaTypeInfo.FirstOrDefault(a => a.AreaTypeName == areaType.AreaTypeName);
                if (existingAreaType != null)
                {
                    return Json(new { code = 1, msg = "区域类别名称已存在，请使用其他名称" });
                }

                db.AreaTypeInfo.Add(areaType);
                db.SaveChanges();

                return Json(new { code = 0, msg = "添加区域类别成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "添加区域类别失败：" + ex.Message });
            }
        }

        // 修改区域类别
        [HttpPost]
        public ActionResult UpdateAreaType(AreaTypeInfo areaType)
        {
            try
            {
                var existingAreaType = db.AreaTypeInfo.Find(areaType.AreaTypeID);
                if (existingAreaType == null)
                {
                    return Json(new { code = 1, msg = "区域类别不存在" });
                }

                // 验证区域类别名称是否已存在（排除当前区域类别）
                var existingWithSameName = db.AreaTypeInfo.FirstOrDefault(a => a.AreaTypeName == areaType.AreaTypeName && a.AreaTypeID != areaType.AreaTypeID);
                if (existingWithSameName != null)
                {
                    return Json(new { code = 1, msg = "区域类别名称已存在，请使用其他名称" });
                }

                // 更新字段
                existingAreaType.AreaTypeName = areaType.AreaTypeName;
                existingAreaType.AreaTypeMark = areaType.AreaTypeMark;

                db.Entry(existingAreaType).State = EntityState.Modified;
                db.SaveChanges();

                return Json(new { code = 0, msg = "修改区域类别成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "修改区域类别失败：" + ex.Message });
            }
        }

        // 删除区域类别
        [HttpPost]
        public ActionResult DeleteAreaType(int id)
        {
            try
            {
                var areaType = db.AreaTypeInfo.Find(id);
                if (areaType == null)
                {
                    return Json(new { code = 1, msg = "区域类别不存在" });
                }

                // 检查该区域类别是否被区域信息表引用
                var isReferenced = db.AreaInfo.Any(a => a.AreaTypeID == id);
                if (isReferenced)
                {
                    return Json(new { code = 1, msg = "该区域类别已被区域信息引用，无法删除" });
                }

                db.AreaTypeInfo.Remove(areaType);
                db.SaveChanges();

                return Json(new { code = 0, msg = "删除区域类别成功" });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "删除区域类别失败：" + ex.Message });
            }
        }

        // 检查区域类别名称是否唯一
        [HttpPost]
        public ActionResult CheckAreaTypeName(string areaTypeName, int? areaTypeId = null)
        {
            try
            {
                var existing = db.AreaTypeInfo.FirstOrDefault(a => a.AreaTypeName == areaTypeName);
                if (existing != null && (areaTypeId == null || existing.AreaTypeID != areaTypeId))
                {
                    return Json(new { code = 1, msg = "区域类别名称已存在" });
                }
                return Json(new { code = 0 });
            }
            catch (Exception ex)
            {
                return Json(new { code = 1, msg = "检查失败：" + ex.Message });
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}